import React, { Component } from 'react'
import { InputGroup, Button, FormControl } from 'react-bootstrap'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'

class InputNumber extends Component {

  state = { num: 1 }

  // 使用shouldComponentUpdate来限制num
  shouldComponentUpdate (nextProps, nextState) {
    const { num } = nextState
    const { maxNum } = this.props
    if (num < 1 || num > maxNum) return false
    else return true
  }

  render () {
    const num = this.state.num
    return (
      <InputGroup>
        <InputGroup.Prepend>
          <InputGroup.Text as = {Button}
                           onClick = {() => this.setState(
                             { num: num - 1 })}>
            <FontAwesomeIcon icon = {'minus'} />
          </InputGroup.Text>
        </InputGroup.Prepend>
        <FormControl className = {'text-center'} type = {'number'}
                     onChange = {(e) => this.setState(
                       { num: e.target.value })}
                     value = {num} />
        <InputGroup.Append>
          <InputGroup.Text as = {Button}
                           onClick = {() => this.setState(
                             { num: num + 1 })}>
            <FontAwesomeIcon icon = {'plus'} />
          </InputGroup.Text>
        </InputGroup.Append>
      </InputGroup>
    )
  }
}

export default InputNumber
